import axios from 'axios'
import { ElMessage } from 'element-plus'

// 创建axios实例
const service = axios.create({                    // 生产环境使用相对路径
    baseURL: 'http://localhost:3001',
    timeout: 10000
})

// 请求拦截器
service.interceptors.request.use(
    config => {
        if (config.method === 'get') {
            config.params = {
                ...config.params,
                _t: Date.now()
            }
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => {
        const res = response.data
        if (res.status === 200) {
            return res.data
        } else if (res.status === 400) {
            ElMessage({
                message: res.message || 'Error',
                type: 'error',
                duration: 5 * 1000
            })
        }
    },
    error => {
        ElMessage({
            message: error.message || 'Error',
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export default service